//
//  Queue.swift
//  SwiftyDSA
//
//  Created by Archer on 2018/8/6.
//  Copyright © 2018年 Archer. All rights reserved.
//

import Foundation

public final class Queue<Element> {
    
    // a Queue does not wrap a Vector but a LinkedList,
    // because we want dequeue as quick as possible
    let _storage: LinkedList<Element>
    
    /// whether the Queue is empty
    public var isEmpty: Bool { return _storage.isEmpty }
    /// Indicates number of elements in Queue
    public var count: Int { return _storage.count }
    
    /// 取队首元素
    public var front: Element? {
        get {
            if _storage.isEmpty { return nil }
            return _storage.first?.value
        }
    }
    
    /// Initialize a empty Queue
    public init() {
        _storage = LinkedList()
    }
    
    /// Initialize a Queue through another Queue
    public init(_ other: Queue<Element>) {
        _storage = LinkedList(other._storage)
    }
    
    /// 入队
    public func enqueue(_ element: Element) {
        _storage.insertAsLast(element)
    }
    
    /// 出队
    public func dequeue() -> Element? {
        guard let firstNode = _storage.first else { return nil }
        return _storage.remove(firstNode)
    }
}

extension Queue: ExpressibleByArrayLiteral {
    public convenience init(arrayLiteral elements: Element...) {
        self.init()
        elements.forEach { _storage.insertAsLast($0) }
    }
}
